package com.didispace.hystrixCollapser;

import com.alibaba.fastjson.JSONArray;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;

@Service
public class UserService {

    @Autowired
    private RestTemplate restTemplate;

    public User find1(Long id) {
        return restTemplate.getForObject("http://USER-SERVICE/find/{1}", User.class, id);
    }

    // p171 使用注解实现请求合并器  p172 通过 batchMethod 属性指定了批量请求的实现方法为 findAll 方法
    // 通过 collapserProperties 属性为合并请求器设置了相关属性，这里使用 @HystrixProperty(name = "timerDelayInMilliseconds",value = "100") 将合并时间窗设置为 100 毫秒
    @HystrixCollapser(batchMethod = "findAll",collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds",value = "100")})
    public Future<User> find(Long id){
        return null;
    }

    @HystrixCommand
    public List<User> findAll(List<Long> ids) {
        // Caused by: rx.exceptions.OnErrorNotImplementedException: java.util.LinkedHashMap cannot be cast to com.didispace.hystrixCollapser.User
        // return restTemplate.getForObject("http://USER-SERVICE/findAll?ids={1}", List.class, StringUtils.join(ids, ","));

        User[] users = restTemplate.getForObject("http://USER-SERVICE/findAll?ids={1}", User[].class, StringUtils.join(ids, ","));
        return Arrays.asList(users);

        // ParameterizedTypeReference<List<User>> res = new ParameterizedTypeReference<List<User>>() {
        // };
        // ResponseEntity<List<User>> resp = restTemplate.exchange("http://HELLO-SERVICE/findAll/{1}",
        //         HttpMethod.GET, null, res, StringUtils.join(ids, ","));
        // return resp.getBody();
    }
}
